package org.dromara.job.processors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.utils.PageUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.vcp.VcpUtil;
import org.dromara.common.vcp.domain.SzSecret;
import org.dromara.device.api.RemoteDeviceService;
import org.dromara.device.api.domain.vo.ApiDeviceVo;
import org.dromara.device.api.enums.RedisKeyConstant;
import org.springframework.stereotype.Component;
import tech.powerjob.worker.core.processor.ProcessResult;
import tech.powerjob.worker.core.processor.TaskContext;
import tech.powerjob.worker.core.processor.sdk.BasicProcessor;
import tech.powerjob.worker.log.OmsLogger;

import java.util.ArrayList;
import java.util.List;

/**
 * 查询设备的状态
 */
@Component
public class DeviceStatusJob  implements BasicProcessor {

    @DubboReference
    private RemoteDeviceService remoteDeviceService;

    @Override
    public ProcessResult process(TaskContext taskContext) {

        OmsLogger logger = taskContext.getOmsLogger();
        logger.info("开始更新设备状态");

        JSONArray objects = updateStatus(logger);
        if (objects.isEmpty()) {
            return new ProcessResult(true, "设备状态任务完成");
        }

        List<ApiDeviceVo> list = new ArrayList<>(objects.size());
        for (Object object : objects) {
            JSONObject jsonObject = JSONUtil.parseObj(object.toString());
            String deviceCode = jsonObject.getStr("deviceCode");
            String status = jsonObject.get("status").toString(); // 接口 1:在线 、0:离线；
            RedisUtils.setCacheMapValue(GlobalConstants.GLOBAL_REDIS_KEY + RedisKeyConstant.Device.DEVICE_STATUS, deviceCode, status);

            status = "0".equals(status) ? "1" : "0"; // 业务 0： 在线 1：离线
            System.out.println("设备号：【" + deviceCode + "】, 状态为： 【" + status + "】");
            logger.info("设备号：【{}】, 状态为： 【{}】", deviceCode, status);
            ApiDeviceVo apiDeviceVo = new ApiDeviceVo();
            apiDeviceVo.setDeviceSn(deviceCode);
            apiDeviceVo.setStatus(status);
            list.add(apiDeviceVo);
        }
        // 批量更新
        remoteDeviceService.updateBatchStatusByDeviceSn(list);
        logger.info("结束更新设备状态");
        return new ProcessResult(true, "更新设备状态完成");
    }

    /**
     * 更新设备状态
     */
    private JSONArray updateStatus(OmsLogger logger) {

        JSONArray jsonArray = new JSONArray();
        List<ApiDeviceVo> result = remoteDeviceService.queryByNotStoreId();
        if (CollUtil.isEmpty(result)) {
            logger.info("未查询到绑定门店的设备");
            return jsonArray;
        }

        int totalPage = PageUtil.totalPage(result.size(), PageUtils.PAGE_SIZE);
        for (int i = 0; i < totalPage; i++) {
            List<ApiDeviceVo> apiDeviceVoList = PageUtils.getPageData(result, i);
            List<SzSecret> szSecrets = BeanUtil.copyToList(apiDeviceVoList, SzSecret.class);
            // 调用云眼API
            JSONArray newArray = VcpUtil.batchOnlineStatusByCodes(szSecrets);
            if (!newArray.isEmpty()) {
                jsonArray.addAll(newArray);
            }

        }

        return jsonArray;

    }
}
